//
//  UIImage+FView.m
//  Foundation
//
//  Created by 新庭 on 2019/8/31.
//

#import "UIImage+FView.h"

@implementation UIImage (FView)

+ (UIImage *)view_imageNamed:(NSString *)name {
    NSBundle *bundle = nil;
    if (!bundle) {
        NSString *bundlePath = [NSBundle.mainBundle pathForResource:@"FView" ofType:@"bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    }
    return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
}

- (UIBezierPath *)fv_boundaryPath {
    UIBezierPath *path = [[UIBezierPath alloc] init];
    
    CGImageRef img = self.CGImage;
    CFDataRef imgData;
    imgData = CGDataProviderCopyData(CGImageGetDataProvider(img));
    
    UInt8 *mPixelBuf = (UInt8 *) CFDataGetBytePtr(imgData);
    
    CGFloat width = CGImageGetWidth(img);
    CGFloat height = CGImageGetHeight(img);
    
    // from top
    NSMutableArray<NSValue *> *boundary = [NSMutableArray arrayWithCapacity:width * 2];
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            int loc = x + (y * width);
            loc *= 4;
            if (mPixelBuf[loc + 3] != 0) {
                [boundary addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
                break;
            }
        }
    }
    
    for (int x = width; x >= 0; x--) {
        for (int y = height; y >= 0; y--) {
            int loc = x + (y * width);
            loc *= 4;
            if (mPixelBuf[loc + 3] != 0) {
                [boundary addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
                break;
            }
        }
    }
    
    [path moveToPoint:[boundary.firstObject CGPointValue]];
    for (NSValue *v in boundary) {
        [path addLineToPoint:v.CGPointValue];
    }
    [path closePath];
    return path;
}

#pragma mark - Private
@end
